<template>
  <div class="soil-data">
    <div v-if="sensorData.length === 0" class="no-data">
      <el-empty description="暂无数据"></el-empty>
    </div>
    <div v-else class="data-grid">
      <div v-for="sensor in sensorData" :key="sensor.id" class="sensor-card">
        <div class="custom-border">
          <div class="sensor-content">
            <div class="sensor-header">
              <div class="sensor-name">{{ getSensorDisplayName(sensor.name) }}</div>
              <div class="status-tag" :class="{ 'online': sensor.connState }">
                在线
              </div>
            </div>
            <div class="sensor-main">
              <div class="sensor-value">
                {{ formatValue(sensor.value, sensor.name) }}
                <span class="unit">{{ getUnit(sensor.name) }}</span>
              </div>
              <div class="sensor-chart">
                <div :id="`chart-${sensor.id}`" class="chart-container">
                </div>
              </div>
            </div>
            <div class="sensor-footer">
              <div class="update-time">
                更新于: {{ formatTime(sensor.timestamp) }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner">
        <i class="el-icon-loading"></i>
        <span>加载中...</span>
      </div>
    </div>
    <div v-if="error" class="error-message">
      {{ error }}
      <el-button type="primary" size="small" @click="fetchData">重试</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch, nextTick } from 'vue'
import { 
  getSensorLatest,
  getSensorHistory
} from '../api/sensor'
import dayjs from 'dayjs'
import * as echarts from 'echarts'

const sensorData = ref([])
const historyData = ref({})
const loading = ref(false)
const error = ref(null)
let charts = ref({})
let refreshTimer = null

// 在这里先声明 cleanup 函数
const cleanup = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
  Object.values(charts.value).forEach(chart => {
    chart?.dispose()
  })
}

// 在组件卸载时调用清理函数
onUnmounted(cleanup)

const props = defineProps({
  displayMode: {
    type: String,
    default: 'detailed' // 'detailed' 或 'key-metrics'
  }
})

// 关键指标列表
const keyMetrics = ['土壤温度', '土壤含水量', '土壤PH值']

// 根据显示模式过滤传感器数据
const filteredSensorData = computed(() => {
  if (props.displayMode === 'key-metrics') {
    return sensorData.value.filter(sensor => keyMetrics.includes(sensor.name))
  }
  return sensorData.value.filter(sensor => !keyMetrics.includes(sensor.name))
})

// 计算最后更新时间
const lastUpdateTime = computed(() => {
  if (sensorData.value.length === 0) return '暂无数据'
  const latestTime = Math.max(...sensorData.value.map(s => new Date(s.timestamp).getTime()))
  return formatTime(new Date(latestTime))
})

// 根据数据类型获取单位和名称
const getSensorInfo = (name) => {
  const info = {
    '土壤含水量': {
      unit: '%',
      name: '土壤含水率',
      icon: 'el-icon-water-cup',
      precision: 1
    },
    '土壤温度': {
      unit: '℃',
      name: '土壤温度',
      icon: 'el-icon-temperature',
      precision: 1
    },
    '土壤电导率': {
      unit: 'us/cm',
      name: '土壤电导率',
      icon: 'el-icon-lightning',
      precision: 1
    },
    '土壤PH值': {
      unit: 'pH',
      name: '土壤PH值',
      icon: 'el-icon-water',
      precision: 2
    },
    '土壤氮含量': {
      unit: 'mg/kg',
      name: '土壤氮含量',
      icon: 'el-icon-notebook-2',
      precision: 0
    },
    '土壤磷含量': {
      unit: 'mg/kg',
      name: '土壤磷含量',
      icon: 'el-icon-notebook-2',
      precision: 0
    },
    '土壤钾含量': {
      unit: 'mg/kg',
      name: '土壤钾含量',
      icon: 'el-icon-notebook-2',
      precision: 0
    },
    '空气温度': {
      unit: '℃',
      name: '空气温度',
      icon: 'el-icon-temperature',
      precision: 1
    },
    '空气相对湿度': {
      unit: '%RH',
      name: '空气相对湿度',
      icon: 'el-icon-water-cup',
      precision: 1
    },
    '光照度': {
      unit: 'Lux',
      name: '光照度',
      icon: 'el-icon-sunny',
      precision: 0
    },
    '二氧化碳': {
      unit: 'ppm',
      name: '二氧化碳',
      icon: 'el-icon-wind-power',
      precision: 0
    }
  }
  return info[name] || {
    unit: '',
    name: name,
    icon: 'el-icon-monitor',
    precision: 0
  }
}

// 获取传感器图标
const getSensorIcon = (dataType) => {
  return getSensorInfo(dataType).icon
}

// 获取折线图配置
const getChartOption = (sensor) => {
  const key = sensor.name.trim()
  const history = historyData.value[key] || []
  
  // 确保数据按时间排序
  const sortedData = history
    .sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp))
    .slice(-24)  // 只取最近24个点
  
  const values = sortedData.map(item => Number(item.value))
  const times = sortedData.map(item => dayjs(item.timestamp).format('HH:mm'))

  // 计算数值范围
  const validValues = values.filter(v => !isNaN(v) && v !== null)
  const min = validValues.length ? Math.min(...validValues) * 0.9 : 0
  const max = validValues.length ? Math.max(...validValues) * 1.1 : 100

  return {
    animation: false, // 禁用动画，提高性能
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const value = params[0].value
        const time = params[0].axisValue
        const info = getSensorInfo(sensor.name)
        return `${time}<br/>${info.name}: ${value.toFixed(info.precision)} ${info.unit}`
      }
    },
    grid: {
      top: 5,
      bottom: props.displayMode === 'key-metrics' ? 15 : 20,
      left: props.displayMode === 'key-metrics' ? 30 : 40,
      right: 20,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: times,
      axisLabel: {
        fontSize: props.displayMode === 'key-metrics' ? 9 : 11,
        color: 'rgba(255, 255, 255, 0.65)',
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      min: min,
      max: max,
      axisLabel: {
        fontSize: props.displayMode === 'key-metrics' ? 9 : 11,
        color: 'rgba(255, 255, 255, 0.65)'
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)'
        }
      }
    },
    series: [{
      type: 'line',
      smooth: true,
      showSymbol: true,
      symbolSize: props.displayMode === 'key-metrics' ? 6 : 8,
      data: values,
      lineStyle: {
        color: '#7ec699',
        width: props.displayMode === 'key-metrics' ? 2 : 3
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(126, 198, 153, 0.3)'
          }, {
            offset: 1,
            color: 'rgba(126, 198, 153, 0.1)'
          }]
        }
      }
    }]
  }
}

// 获取历史数据
const fetchHistoryData = async (sensor) => {
  try {
    // 从传感器名称中提取类型
    let type = ''
    switch(sensor.name) {
      case '土壤含水量':
        type = 'moisture'
        break
      case '土壤温度':
        type = 'temperature'
        break
      case '土壤氮含量':
        type = 'nitrogen'
        break
      case '土壤磷含量':
        type = 'phosphorus'
        break
      case '土壤钾含量':
        type = 'potassium'
        break
    }
    
    if (!type) {
      console.warn(`未知的传感器类型: ${sensor.name}`)
      return []
    }

    const history = await getSensorHistory(type, {
      startTime: dayjs().subtract(24, 'hour').format('YYYY-MM-DD HH:mm:ss'),
      endTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
    })
    return history
  } catch (error) {
    if (error.response?.status === 404) {
      console.warn(`${sensor.name}暂无历史数据`)
    } else {
      console.error(`获取${sensor.name}历史数据失败:`, error)
    }
    return []
  }
}

// 获取传感器数据
const fetchData = async () => {
  loading.value = true
  error.value = null
  try {
    const data = await getSensorLatest()
    console.info('暂无传感器数据')
    
    if (!Array.isArray(data) || data.length === 0) {
      console.info('暂无传感器数据')
      sensorData.value = []
      return
    }

    // 按类型分组最新数据
    const latestData = data.reduce((acc, item) => {
      const sensorType = item.type || item.name || ''
      const type = sensorType.toLowerCase().replace('soil_', '').replace('土壤', '')
      if (!acc[type] || new Date(item.timestamp) > new Date(acc[type].timestamp)) {
        acc[type] = item
      }
      return acc
    }, {})

    if (process.env.NODE_ENV === 'development') {
      console.debug('传感器数据分组:', latestData)
    }

    // 构建传感器数据
    sensorData.value = [
      {
        id: 1,
        name: '土壤含水量',
        value: Number(latestData['moisture']?.value || latestData['含水量']?.value || 0),
        timestamp: latestData['moisture']?.timestamp || latestData['含水量']?.timestamp,
        connState: 1,
        status: 1
      },
      {
        id: 2,
        name: '土壤温度',
        value: Number(latestData['temperature']?.value || latestData['温度']?.value || 0),
        timestamp: latestData['temperature']?.timestamp || latestData['温度']?.timestamp,
        connState: 1,
        status: 1
      },
      {
        id: 3,
        name: '土壤氮含量',
        value: Number(latestData['nitrogen']?.value || latestData['氮含量']?.value || 0),
        timestamp: latestData['nitrogen']?.timestamp || latestData['氮含量']?.timestamp,
        connState: 1,
        status: 1
      },
      {
        id: 4,
        name: '土壤磷含量',
        value: Number(latestData['phosphorus']?.value || latestData['磷含量']?.value || 0),
        timestamp: latestData['phosphorus']?.timestamp || latestData['磷含量']?.timestamp,
        connState: 1,
        status: 1
      },
      {
        id: 5,
        name: '土壤钾含量',
        value: Number(latestData['potassium']?.value || latestData['钾含量']?.value || 0),
        timestamp: latestData['potassium']?.timestamp || latestData['钾含量']?.timestamp,
        connState: 1,
        status: 1
      }
    ]

    // 打印每个传感器的值
    sensorData.value.forEach(sensor => {
      console.log(`${sensor.name} value:`, sensor.value)
    })

    console.log('Processed sensor data:', sensorData.value)

    // 获取每个传感器的历史数据
    for (const sensor of sensorData.value) {
      console.log(`Fetching history for ${sensor.name}`)
      const history = await fetchHistoryData(sensor)
      console.log(`History data for ${sensor.name}:`, history)
      
      // 处理历史数据格式
      const formattedHistory = history.map(item => ({
        value: Number(item.value || 0),
        timestamp: item.timestamp || item.create_time
      })).filter(item => !isNaN(item.value)) // 过滤掉无效值

      historyData.value[sensor.name] = formattedHistory
    }

    console.log('Final sensor data:', sensorData.value)
    console.log('History data:', historyData.value)
  } catch (error) {
    console.error('获取传感器数据失败:', error)
    error.value = '获取数据失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '暂无数据'
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
}

// 获取单位
const getUnit = (name) => {
  return getSensorInfo(name).unit
}

// 格式化数值
const formatValue = (value, name) => {
  if (value === null || value === undefined) return '0'
  const precision = getSensorInfo(name).precision
  const numValue = Number(value)
  if (isNaN(numValue)) {
    console.warn(`Invalid value for ${name}:`, value)
    return '0'
  }
  return numValue.toFixed(precision)
}

// 获取传感器名称显示
const getSensorDisplayName = (name) => {
  const info = getSensorInfo(name)
  return info.name || name
}

// 初始化图表
const initChart = (sensor) => {
  if (!charts.value[sensor.id]) return;
  
  const chartDom = document.getElementById(`chart-${sensor.id}`);
  if (!chartDom) {
    console.warn(`Chart DOM not found for sensor ${sensor.id}`);
    return;
  }

  // 等待 DOM 渲染完成
  nextTick(() => {
    if (chartDom.clientWidth === 0 || chartDom.clientHeight === 0) {
      console.warn(`Invalid chart dimensions for sensor ${sensor.id}`);
      setTimeout(() => initChart(sensor), 100); // 延迟重试
      return;
    }

    // 如果已存在的图表实例，先销毁
    if (charts.value[sensor.id]) {
      charts.value[sensor.id].dispose();
    }

    const chart = echarts.init(chartDom);
    charts.value[sensor.id] = chart;
    
    const option = getChartOption(sensor);
    chart.setOption(option);
  });
}

// 监听数据变化，更新图表
watch(() => sensorData.value, () => {
  nextTick(() => {
    if (sensorData.value && Array.isArray(sensorData.value)) {
      sensorData.value.forEach(sensor => {
        if (sensor && sensor.id) {
          initChart(sensor)
        }
      })
    }
  })
}, { deep: true })

// 分离温度传感器数据和其他数据
const mainSensorData = computed(() => {
  return sensorData.value.filter(sensor => sensor.name !== '土壤温度')
})

const temperatureSensor = computed(() => {
  return sensorData.value.find(sensor => sensor.name === '土壤温度')
})

// 组件挂载时的处理
onMounted(() => {
  // 初始化数据
  fetchData()
  
  // 设置定时刷新
  refreshTimer = setInterval(fetchData, 300000) // 每5分钟刷新一次
  
  // 监听窗口大小变化
  const handleResize = () => {
    Object.values(charts.value).forEach(chart => {
      chart?.resize()
    })
  }
  window.addEventListener('resize', handleResize)
  
  // 返回清理函数
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
  })
})
</script>

<style scoped>
.soil-data {
  width: 100%;
  height: 100%;
  padding: 0;
}

.data-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px 15px;
  padding: 10px;
}

.sensor-card {
  height: 150px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  overflow: hidden;
}

.custom-border {
  height: 100%;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
}

.sensor-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.sensor-header {
  padding: 8px 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.sensor-name {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.85);
  font-weight: 500;
}

.status-tag {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
  background: rgba(82, 196, 26, 0.2);
  color: #52c41a;
}

.status-tag.online {
  background: rgba(82, 196, 26, 0.2);
  color: #52c41a;
}

.sensor-main {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
}

.sensor-value {
  font-size: 28px;
  color: #1890ff;
  font-weight: 500;
  min-width: 100px;
}

.unit {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.65);
  margin-left: 4px;
}

.sensor-chart {
  width: 180px;
  height: 80px;
}

.chart-container {
  width: 100%;
  height: 100%;
}

.update-time {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.45);
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.loading-spinner {
  color: #7ec699;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.loading-spinner i {
  font-size: 24px;
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.error-message {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  gap: 10px;
}

/* 关键指标卡片特殊样式 */
.key-metrics .sensor-chart {
  width: 120px;
  height: 60px;
}

.key-metrics .sensor-value {
  font-size: 24px;
  min-width: 80px;
}

/* 响应式布局 */
@media screen and (max-width: 1366px) {
  .data-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px 12px;
  }
  
  .sensor-card {
    height: 130px;
  }
  
  .sensor-chart {
    width: 150px;
    height: 65px;
  }
}

@media screen and (max-width: 1024px) {
  .data-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style> 